package com.vik.webgallery.web;

import java.util.logging.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.vik.webgallery.beans.User;
import com.vik.webgallery.persistence.UserMapper;
import com.vik.webgallery.validators.UserValidator;


@Controller
public class RegistrationController {

	@Autowired
	private UserMapper userMapper;
	
	@RequestMapping(value="/registration", method=RequestMethod.GET)
	public String registration(Model model) {
		
		User user = new User();
		model.addAttribute("user", user);
		return "registration";
		
	
	}
	
	
	@RequestMapping(value="/registration", method=RequestMethod.POST)
	public String registration(@ModelAttribute User user, Model model, BindingResult result) {
		new UserValidator().validate(user, result);
		
		if (result.hasErrors()){
			return "registration";
		}else{
			if(userMapper.getUser(user.getUserName()) != null)
			{
				model.addAttribute("errMsg", "User allready exists.");
				return "registration";
			}
			user.setRole(User.STANDARD_USER);
			user.setEnabled(true);
			userMapper.insertUser(user);
			
			return "redirect:/registrationDone";
		}
	}
	
	
	@RequestMapping(value="/registrationDone", method=RequestMethod.GET)
	public String registrationDone(Model model) {
		return "registrationDone";
	}
}
